#!/usr/bin/env python
# -*- coding: utf-8 -*-


import paramiko  # 用于调用scp命令
from scp import SCPClient

from .utils import tools
from .utils import sqldb
from .utils import odoorpc
from .utils.control import Control

import time
import os
import logging  # 引入logging模块

import datetime

from .utils import command


logger = logging.getLogger()
# logger.info('set loggin ok')


def get_rpi_debug(conf_file):
    rpi_debug = conf_file['options'].get('rpi_debug')
    rpi_debug = rpi_debug and eval(rpi_debug)
    # logger.info('rpi_debug is: %s' % rpi_debug)
    return rpi_debug


def check_network(num0=None):
    import urllib.request
    url = "http://www.baidu.com"

    num = num0 or 4
    status = False
    while num and not status:
        num = num - 1
        # print('num,', num)
        try:
            status = urllib.request.urlopen(url)
            return status
        except:
            time.sleep(2)
            continue

    return status


def get_db(conf_file):
    options = conf_file.get('options')
    rpi_debug = get_rpi_debug(conf_file)

    # print('db options,', options)
    if rpi_debug:
        # logger.info('rpi_debug is %s, local db need not' % rpi_debug)
        return None

    local_db = options.get('local_db')
    db = sqldb.get_db(local_db)
    # logger.info('local db is ok, db file: %s' % local_db)
    return db


def get_odoo(conf_file, gatewate_code):
    options = conf_file.get('options')
    odoo = odoorpc.get_odoo(gatewate_code=gatewate_code,  **options)
    rpi_debug = get_rpi_debug(conf_file)
    if rpi_debug:
        pass
        # logger.info('rpi_debug is %s, odoo need not' % rpi_debug)
    else:
        pass
        # logger.info('connect odoo is ok, session_id=: %s' % odoo.session_id)
    return odoo


def get_port(conf_file):
    # 读配置文件
    # port = '/dev/ttyS0'  # 虚拟机的串口
    # port = '/dev/ttyAMA0'  # 树莓派的串口
    port = conf_file['options']['serial_port']
    # logger.info('serial port is: %s' % port)
    return port


def upload_log(gatewate_code):
    host = '106.13.191.63'
    port = 22
    username = 'root'
    password = 'root@szdw2020'

    remote_path = "/var/log/odoo/thewell"
    log_file = 'rpi_main.log'

    tt = time.time()
    tt = time.localtime(time.time())

    dt = tt.tm_year * 10000 + tt.tm_mon * 100 + tt.tm_mday
    tm = tt.tm_hour * 10000 + tt.tm_min * 100 + tt.tm_sec
    remote_file = '%s/%s_%s_%s.log' % (remote_path, gatewate_code, dt, tm)

    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
    ssh_client.connect(host, port, username, password)
    scpclient = SCPClient(ssh_client.get_transport(), socket_timeout=15.0)

    try:
        scpclient.put(log_file, remote_file)

    except FileNotFoundError as e:
        print(e)
        print("系统找不到指定文件" + log_file)
    else:
        print("文件上传成功")
    ssh_client.close()


def main():
    log_file = 'rpi_main.log'
    with open(log_file, "w", encoding="utf-8") as f2:
        f2.write("")

    conf_file = tools.get_config()
    # logger.info('cfg file: %s' % conf_file)
    # 设置 运行日志文件
    logging_level = conf_file['options'].get('logging_level') or 'INFO'
    tools.set_logging('rpi_main', logging_level)

    # admin_debug = conf_file['options'].get('admin_debug')
    # admin_debug = admin_debug and eval(admin_debug)
    # # logger.info('admin_debug is: %s' % admin_debug)

    # # rpi_debug = get_rpi_debug(conf_file)
    # # logger.info('rpi_debug is: %s' % rpi_debug)

    # # 1 初始化 设置. 串口号, 连接 本地数据库
    # port = get_port(conf_file)
    # db = get_db(conf_file)

    # # 2 启动 主控线程, 接收 从机的应答
    # # logger.info('init contorl')
    # odoo = None
    # ctrl = Control(dev=port, host='host', odoo=odoo,  db=db)
    # # logger.info('init contorl ok')

    # # 3 下发通知, 等待获取 gateway_code
    # now_timestamp = 0
    # gatewate_code = ctrl.send_ready(now_timestamp)
    # # gatewate_code = ctrl.send_ready(now_timestamp)
    # # return None

    # if not gatewate_code:
    #     logger.info('slave no ack, quit and not shutdown')
    #     return None

    gatewate_code = '000000000002'

    upload_log(gatewate_code)

    # # 关机
    # sudo_password = "root"
    # command = "sudo shutdown -h now"
    # os.system('echo %s | sudo -S %s' % (sudo_password, command))
